<?php
/**
 * User: hda
 * Date: 2017/4/25
 * Time: 9:38
 * Progress: 0%
 */

namespace app\index\controller;


use icontroller\delivery\index\ILogin;
use library\tencent\wechat\admin_wechat\Settings;
use library\tencent\wechat\common\WechatOAuth;
use library\tencent\wechat\wechat_index\OAuthManagement;
use library\tencent\wechat\wechat_index\UserInfoManagement;
use model\AccountRole;
use phpDocumentor\Reflection\Location;
use think\Config;
use think\Controller;
use think\Cookie;
use think\Request;

class Login extends Controller implements ILogin
{
    public function index()
    {

        if (Cookie::get(Config::get('const.cookie_name_delivery'))) {
            $this->redirect('index/Order/index');
        }

        global $DELIVERY;
        $id = input('id');

        if ($id) {
            $account = AccountRole::get(["account_id"=>$id,"role_id"=>2] );
            if (!$account){
                $this->error("对不起，您不是配送员");
            }
            $DELIVERY = $id;
            $url = Cookie::get('delivery_redirect_url');
            Cookie::delete('delivery_redirect_url');
            Cookie::set(Config::get('const.cookie_name_delivery'), $id);
            if ($url) {
                header("Location:{$url}");
                exit();
            } else {
                $this->redirect('index/Order/index');
            }
        } else {
            return $this->fetch();
        }
    }
    public function my_error(){
        return view();
    }


    /**
     * 微信登录
     * @param $scope
     * @param $parent_id
     * @param $url
     * @return mixed
     */
    public function wechat($scope = 'snsapi_base', $parent_id = null)
    {
//        $url=$_SERVER['HTTP_REFERER'];
//        $url=Cookie::get('wechat_redirect_url');
        $state = array('flag' => 'login');

        if ($parent_id) {
            $state['parent_id'] = $parent_id;
        }
        if ($scope == 'snsapi_userinfo') {
            $state = array('flag' => 'save_info');
        }

        $cfg = Settings::get('wechat_mp_config');
        $redirectUri = $this->request->domain() . url('Login/callback');

        WechatOAuth::authorizeRedirect($cfg['app_id'], $redirectUri, WechatOAuth::stateEncode($state), $scope);
    }

    /***
     * @param $code
     * @param $state
     * 微信回调
     */
    public function callback($code = null, $state = null)
    {
        if (empty($code) || empty($state)) {
            exit('Error: Invalid Parameter');
        }
        $state = WechatOAuth::stateDecode($state);

        if (!is_array($state)) {
            exit('Error: Invalid State');
        }
        $cfg = Settings::get('wechat_mp_config');

        //通过code换取网页授权access_token
        $result = WechatOAuth::getAccessToken($cfg['app_id'], $cfg['secret'], $code);
      //  print_r($result);die();
        //openid信息

        $openid_msg = $result['data'];
        $openid_msg['user_info'] = '';
        $openid_msg['subscribe'] = '';
        if (array_key_exists('parent_id', $state)) {
            $openid_msg['parent_id'] = $state['parent_id'];
        }


        if (!$result['success']) {
            exit(sprintf('Error(%d): %s', $result['code'], $result['message']));
        }
        if ($state['flag'] == 'login') {//静默登录
            if (OAuthManagement::if_exist_openid($result['data']) == false) {
                $this->wechat('snsapi_userinfo');
            }

        } else {//授权登录
            $oauth_userinfo = WechatOAuth::getUserInfo($result['data']['access_token'], $result['data']['openid']);
            //新增user_wechat_oauth一条记录
            $openid_msg['user_info'] = $oauth_userinfo['data'];
            //获取用户信息
            $userInfo = UserInfoManagement::userInfo($result['data']['openid']);
            $openid_msg['subscribe'] = $userInfo->getData()['subscribe'];

        }
        $openid_msg['parent_id'] =  Cookie::get('parent_id');

        $account = OAuthManagement::login($openid_msg, $this->request->ip(), false);
//        var_dump($account);die();
//        var_dump(Config::get('const.cookie_name_wechat'));die();
        Cookie::set(Config::get('const.cookie_name_delivery'), $account['id']);


        $url = Cookie::get('delivery_redirect_url');
        if ($url) {
            $this->redirect($url);
            exit();
        }
        $this->redirect(url('index/Order/index'));

    }

    public function logout()
    {
        Cookie::set(Config::get('const.cookie_name_delivery'), null);
        $this->redirect('index/Login/index');
    }
}